import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { Base64 } from 'js-base64'
import router, { resetRouter, updateRouter } from '@/router'
import store from '@/store'
import { menu } from 'caniuse-lite/data/features'
// import { Message } from 'element-ui'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    permissions: [],
    id: null,
    bubbles: {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ID: (state, id) => {
    state.id = id
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  },
  SET_BUBBLES: (state, data) => {
    state.bubbles = { ...state.bubbles, [data.routeName]: data.bubble }
  }
}
const menusSetting = (resolve, data) => {
  const roles = data.roles
  const name = data.user.userName
  const id = data.user.userId
  const menus = data.menus
  if (data.hasUpdateRight || data.hasUpdateRole) {
    // resetRouter()
    updateRouter(menus)
  }
  // roles must be a non-empty array
  // if (id !== 1 && (!roles || roles.length <= 0)) {
  //   Message({
  //     message: '该用户未设置角色,请联系管理员!',
  //     type: 'error',
  //     duration: 5 * 1000
  //   })
  //   reject('该用户未设置角色,请联系管理员!')
  // }
  store.commit('permission/SET_ROUTES', menus)
  store.commit('user/SET_ROLES', roles)
  store.commit(
    'user/SET_PERMISSIONS',
    data.permissions.map((item) => item.rightCode)
  )
  store.commit('user/SET_NAME', name)
  store.commit('user/SET_ID', id)
  resolve(menus)
}
const actions = {
  menusSetting({ commit, dispatch }, data) {
    const roles = data.roles
    const name = data.user.userName
    const id = data.user.userId
    const menus = data.menus
    if (data.hasUpdateRight || data.hasUpdateRole) {
      // resetRouter()
      updateRouter(menus)
    }
    // roles must be a non-empty array
    // if (id !== 1 && (!roles || roles.length <= 0)) {
    //   Message({
    //     message: '该用户未设置角色,请联系管理员!',
    //     type: 'error',
    //     duration: 5 * 1000
    //   })
    //   reject('该用户未设置角色,请联系管理员!')
    // }
    store.commit('permission/SET_ROUTES', menus)
    store.commit('user/SET_ROLES', roles)
    store.commit(
      'user/SET_PERMISSIONS',
      data.permissions.map((item) => item.rightCode)
    )
    store.commit('user/SET_NAME', name)
    store.commit('user/SET_ID', id)
    dispatch('permission/generateRoutes', menus)
  },
  // user login
  login({ commit }, userInfo) {
    const { loginName, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ loginName: loginName.trim(), password: password })
        .then((response) => {
          commit('SET_TOKEN', response.user.roleId)
          setToken(response.user.roleId)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then((response) => {
          menusSetting(resolve, response.data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      // removeToken()
      logout(state.token)
        .then(() => {
          removeToken() // must remove  token  first
          resetRouter()
          commit('RESET_STATE')
          localStorage.removeItem(Base64.encode('account'))
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },
  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    router.addRoutes(accessRoutes)
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
